
import { v4 as uuidv4 } from 'uuid'
export default {
  data() {
    const _this = this
    return {
      windowSize: [0, 0],
      chartId: `echart-line-${uuidv4()}`,		// 用UUID生成图表id，防止id重复
      chart: { map: null, chartData: [] },
      shadowColors: {
        '#12B9A3': 'rgba(18, 185, 163, .4)',
        '#FEB81D': 'rgba(254, 184, 29, .4)',
        '#3D98F1': 'rgba(61, 152, 241, .4)',
        '#F15643': 'rgba(241, 86, 67, .4)'
      },
      chartColors: [], // 自定义图列颜色集合
      echartOption: {
        title: {
          text: '折线图',
          show: false
        },
        color: ['#12B9A3', '#FEB81D', '#3D98F1', '#F15643'], // 绿黄蓝红
        tooltip: {
          trigger: 'axis',
          textStyle: {
            color: '#333333',
            fontFamily: 'PFZH',
            fontSize: 12,
            lineHeight: 26
          },
          axisPointer: {
            type: 'line',
            lineStyle: {
              type: 'solid',
              color: '#FFD5CB',
              width: 2,
              shadowBlur: 16,
              shadowColor: '#F15643',
              shadowOffsetX: 0,
              shadowOffsetY: 0
            }
          },
          extraCssText: 'z-index: 9', // 设置层级
          formatter(params) {
            let tipMsg = `时间: ${params[0].name}<br>`
            // const color = ['color-green', 'color-yellow', 'color-blue', 'color-red']
            for (const i in params) {
              const item = params[i]
              // class='${color[i]}'
              tipMsg += `${item.seriesName}: <span style="color:${item.color}">${_this.foramtThousand(Number(item.data).toFixed(2))}</span> <br>`
            }
            return `<div class="echart-tooltip-content">${tipMsg}</div>`
          }
        },
        legend: {
          data: [], // ['今年', '去年'],
          show: true,
          align: 'left',
          left: 0,
          top: 0,
          padding: [0, 0, 5, 5],
          lineStyle: {
            opacity: 0
          },
          textStyle: {
            color: '#888888',
            fontFamily: 'PFZH'
          }
        },
        grid: {
          left: '5',
          right: '10',
          bottom: '0',
          top: '40',
          containLabel: true,
          show: false
        },
        toolbox: {
          show: false,
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          // boundaryGap: false, // x轴左右留白
          boundaryGap: ['10%', '10%'],
          data: [],
          axisLine: {
            show: false
          },
          axisTick: {
            show: false // x轴刻度隐藏
          },
          axisLabel: { // 坐标轴字体颜色
            color: '#CCCCCC'
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: { // 坐标轴字体颜色
            color: '#CCCCCC'
          }
        },
        series: [
          /* {
            name: '今年',
            type: 'line',
            smooth: true, // 是否平滑曲线显示
            symbolSize: 8,
            lineStyle: {
              color: '#12B9A3', // 绿色
              // width: 3,
              shadowBlur: 2,
              shadowColor: 'rgba(18, 185, 163, .4)',
              shadowOffsetX: 0,
              shadowOffsetY: 8
            },
            tooltip: {
              textStyle: {
                color: '#12B9A3'
              }
            },
            data: []
          },
          {
            name: '去年',
            type: 'line',
            smooth: true, // 是否平滑曲线显示
            symbolSize: 8,
            lineStyle: {
              color: '#FEB81D', // 黄色
              // width: 3,
              shadowBlur: 2,
              shadowColor: 'rgba(254, 184, 29, .4)',
              shadowOffsetX: 0,
              shadowOffsetY: 8
            },
            data: []
          } */
        ]
      },
      seriesItem: {
        name: '今年',
        type: 'line',
        smooth: true, // 是否平滑曲线显示
        symbolSize: 6,
        lineStyle: {
          color: '#12B9A3', // 绿色
          // width: 3,
          shadowBlur: 2,
          shadowColor: 'rgba(18, 185, 163, .4)',
          shadowOffsetX: 0,
          shadowOffsetY: 8
        },
        tooltip: {
          textStyle: {
            color: '#12B9A3'
          }
        },
        data: []
      }
    }
  },
  created() {
    if (this.chartColors && this.chartColors.length) {
      this.$set(this.echartOption, 'color', this.chartColors)
    }
    if (this.legendData && this.legendData.length) {
      const seriesConfig = []
      this.legendData.forEach((name, index) => {
        const color = this.echartOption.color[index] || '' // 颜色
        const shadowColor = this.shadowColors[color] || '' // 阴影
        const lineStyle = { ...this.seriesItem.lineStyle, ...{ color, shadowColor }}
        const tooltip = { ...this.seriesItem.tooltip, ...{ textStyle: { color }}}
        const seriesItem = { ...this.seriesItem, ...{ name, lineStyle, tooltip }}
        seriesConfig.push(seriesItem)
      })
      this.$set(this.echartOption, 'series', seriesConfig)
      this.$set(this.echartOption.legend, 'data', this.legendData)
    }
  },
  watch: {
    windowSize(val, oldVal) {
      this.chart.map.resize()
    }
  },
  mounted() {
    this.initChart()
    this.$nextTick(() => {
      this.drawChart()
    })
  },
  methods: {
    initChart() {
      this.windowSize = [document.body.clientWidth, document.body.clientHeight]
      window.addEventListener('resize', () => {
        this.windowSize = [document.body.clientWidth, document.body.clientHeight]
      })
      this.chart.map = this.$echarts.init(document.getElementById(this.chartId))
      window.onresize = () => {
        this.chart.map.resize()
      }
    },
    async drawChart() {
      if (this.chart.map) {
        this.chart.map.dispatchAction({
          type: 'hideTip'
        })
      }
      this.chart.map.showLoading({
        color: '#12B9A3',
        fontFamily: 'PFZH',
        textColor: '#CCCCCC',
        fontSize: 14,
        lineWidth: 2
      })		// loading样式
      await this.getChartData()
      this.chart.map.hideLoading()			// 隐藏loading样式
      const chartData = this.chart.chartData

      // ======= 过滤为0的数据，TODO:待确定是否全部过滤 ==============
      const emptyIndexTmp = [] // y轴为0的索引
      chartData.seriesData.forEach(item => {
        item.forEach((v, index) => {
          if (Number(v || 0) === 0) {
            emptyIndexTmp.push(index)
          }
        })
      })

      /*  const emptyIndexs = [...new Set(emptyIndexTmp)]
      emptyIndexs.forEach(index => {
        chartData.xAxisData.splice(index, 1) // 移除数据为0的X轴数据
        chartData.seriesData.forEach(item => {
          item.splice(index, 1) // 移除数据为0的数据
        })
      }) */

      // ===============================================================

      // 模拟延迟加载数据
      const option = this.echartOption // JSON.parse(JSON.stringify(this.echartOption))
      // 设置月份
      option.xAxis.data = chartData.xAxisData // X轴数据
      // 设置数据
      for (const i in chartData.seriesData) {
        option.series[i].data = chartData.seriesData[i]
      }
      this.chart.map.clear()
      this.chart.map.setOption(option)

      this.$nextTick(() => {
        setTimeout(() => {
          this.chart.map.resize()
        }, 300)
      })

      /* if (this.activeIndex > -1) {
        // 设置高亮
        setTimeout(() => {
          this.chart.map.dispatchAction({
            type: 'select',
            // type: 'highlight',
            dataIndex: this.activeIndex
          })
          this.chart.map.dispatchAction({
            type: 'showTip',
            dataIndex: this.activeIndex
          })
          console.log('当前选中x轴Index', this.activeIndex)
        }, 4000)
      } */

      // 高亮时触发
      this.chart.map.on('highlight', (params) => {
        if (params && params.batch && params.batch.length) {
          const batchItem = params.batch[0]
          const xIndex = batchItem.dataIndex
          this.getxAxisSelectData && this.getxAxisSelectData(xIndex)
        }
      })
    }
  }
}
